extends Node
const CONFIG_PATH = "user://settings.cfg"
@onready var animation_player:AnimationPlayer = $AnimationPlayer
@onready var title_scene = preload("res://scenes/ui/title_scene.tscn");
@onready var complete_scene = preload("res://scenes/ui/game_complete.tscn");
@onready var first_scene = preload("res://scenes/world/world01.tscn")

# 金币收集
signal  coins_change
var coins_collected:int = 0
var coins_pending:int:
	set(value):
		coins_pending = value
		coins_change.emit()
	
func get_coins():
	return coins_collected+coins_pending

# 死亡次数
var death_total:int = 0
func get_death_total():
	return death_total

# 完成时间
var start_at:float
var end_at:float
func get_complete_time():
	return int(end_at - start_at)

##### 1. 音效设置
const BUS_BGM=1
const BUS_SFX=2

var bgm_enable:  
	get: return AudioServer.is_bus_mute(BUS_BGM)
	set(value): AudioServer.set_bus_mute(BUS_BGM, value)
var sfx_enable:  
	get: return AudioServer.is_bus_mute(BUS_SFX)
	set(value): AudioServer.set_bus_mute(BUS_SFX, value)

func toggle_bgm():
	bgm_enable = not bgm_enable
	save_config()
	
func toggle_sfx():
	sfx_enable = not sfx_enable
	save_config()
	
func _ready():
	start_at = Time.get_unix_time_from_system()
	end_at = start_at
	load_config()

#### 2. 场景设置
func start_game():
	
	
	
	coins_collected = 0
	coins_pending = 0
	death_total = 0
	start_at = Time.get_unix_time_from_system()
	end_at = start_at
	
	_animation_to_scene(first_scene);
	
func complete_game():
	end_at = Time.get_unix_time_from_system()
	#_animation_to_scene(complete_scene)
	get_tree().change_scene_to_packed(complete_scene)
	
func back_to_title():
	_animation_to_scene(title_scene);
	
func reload_world():
	coins_pending = 0
	death_total +=1
	
	animation_player.play_backwards("fade-in")
	await animation_player.animation_finished
	get_tree().reload_current_scene()
	animation_player.play("fade-in")

func go_to_world(packed_scene):
	coins_collected += coins_pending
	_animation_to_scene(packed_scene)

func _animation_to_scene(packed_scene):
	animation_player.play_backwards("fade-in")
	await animation_player.animation_finished
	get_tree().change_scene_to_packed(packed_scene)
	animation_player.play("fade-in")

func set_paused(paused):
	get_tree().paused = paused
	
## 游戏保存
func save_config():
	var file = ConfigFile.new()
	file.set_value("audio","bgm_enable", bgm_enable)
	file.set_value("audio","sfx_enable", sfx_enable)
	var err = file.save(CONFIG_PATH)
	if err!=OK:
		push_error("failed to save config:%d", err)

func load_config():
	var file = ConfigFile.new()
	var err = file.load(CONFIG_PATH)
	if err==OK:
		bgm_enable = file.get_value("audio","bgm_enable", true)
		sfx_enable = file.get_value("audio","sfx_enable", true)
	else:
		bgm_enable = true
		sfx_enable = true
		push_warning("failed to load config:%d",err)
